package institution

import (
	"context"
	"errors"
	"feng-che.com/server/driver-quiz/internal/constants"
	"feng-che.com/server/driver-quiz/internal/dep_db"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"mongoDB"
)

// Vehicle 考场模拟培训车辆
type Vehicle struct {
	mongoDB.MongoDefaultModelNonID `bson:"basic"`
	ID                             primitive.ObjectID   `bson:"_id,omitempty" json:"id"`
	VehicleExamType                constants.ExamCourse `bson:"vehicle_type" json:"vehicleType"`     // 车辆类型对应考试科目
	VehicleBrand                   string               `bson:"vehicle_brand" json:"vehicleBrand"`   // 车辆品牌
	VehicleModel                   string               `bson:"vehicle_model" json:"vehicleModel"`   // 车辆型号
	VehicleColor                   string               `bson:"vehicle_color" json:"vehicleColor"`   // 车辆颜色
	CarNumber                      string               `bson:"car_number" json:"carNumber"`         // 车牌号码
	MachineSN                      string               `bson:"machine_sn" json:"machineSN"`         // 模拟器编码
	MachineBrand                   string               `bson:"machine_brand" json:"machineBrand"`   // 模拟器品牌
	GearBox                        constants.GearBox    `bson:"gear_box" json:"gearBox"`             // 变速箱
	EPower                         bool                 `bson:"e_power" json:"ePower"`               // 电动车
	InstitutionID                  primitive.ObjectID   `bson:"institution_id" json:"institutionID"` // 归属场地
}

func (v *Vehicle) Save(ctx context.Context, updateOptions ...*options.UpdateOptions) (*mongo.UpdateResult, error) {
	if v.ID.IsZero() {
		v.ID = primitive.NewObjectID()
	}
	var opts []*options.UpdateOptions
	if len(updateOptions) > 0 && updateOptions[0] != nil {
		opts = updateOptions
	} else {
		opts = append(opts, options.Update().SetUpsert(true))
	}
	result, err := v.GetCollection().UpdateByID(ctx, v.ID, bson.D{
		{"$set", v},
	}, opts...)
	return result, err
}

func (v *Vehicle) Update(ctx context.Context, dataFields *bson.D, opts ...*options.UpdateOptions) error {
	if v.ID.IsZero() {
		return errors.New("没有带入id")
	}
	*dataFields = append(*dataFields, bson.E{Key: "$set", Value: bson.D{*mongoDB.CommonUpdateTimeFieldWithCurrentTime()}})
	_, err := v.GetCollection().UpdateByID(ctx, v.ID, *dataFields, opts...)
	return err
}

func (v *Vehicle) Delete(ctx context.Context) error {
	if v.ID.IsZero() {
		return errors.New("没有带入id")
	}
	delFiled := bson.D{}
	fields := mongoDB.CommonDeleteWriteFields()
	for _, i2 := range *fields {
		delFiled = append(delFiled, i2)
	}
	return v.Update(ctx, &bson.D{
		{"$set", delFiled},
	})
}

func (v *Vehicle) GetCollectionName() string {
	return "vehicle"
}

func (v *Vehicle) GetCollection() *mongo.Collection {
	name := v.GetCollectionName()
	return dep_db.ObjectCollection(&name)
}
